package com.zhp.controller.login;

import com.zhp.common.Constant;
import com.zhp.controller.BaseController;
import com.zhp.model.User;
import com.zhp.service.DeptService;
import com.zhp.service.UserInfoService;
import com.zhp.service.UserService;
import com.zhp.service.impl.DeptServiceImpl;
import com.zhp.service.impl.UserInfoServiceImpl;
import com.zhp.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/login/*")
public class LoginController extends BaseController {

    private UserService userService = new UserServiceImpl();

    public void toLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String rememberMe = req.getParameter("rememberMe");
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", username);
        List<User> userList = userService.findByT(map);
        if (userList == null || userList.size() == 0) {
            req.getSession().setAttribute("loginMsg", "账户不存在");
        } else {
            if (password.equals(userList.get(0).getPassword())) {
                if (null != rememberMe) {
                    Cookie cookie = new Cookie("username", username);
                    cookie.setMaxAge(Constant.MAX_COOKIR_TIME);
                    cookie.setPath("/");
                    resp.addCookie(cookie);
                }

                //跟新登录时间
                userService.updateLoginTime(userList.get(0).getId());
                //将真实信息查出来,响应给主页面
                Map<String, Object> userinfomap = userService.findUserBaseInfo(username);
                req.getSession().setAttribute("userinfomap", userinfomap);
                req.getSession().setAttribute(req.getSession().getId(), userinfomap.get("userId").toString());
                resp.sendRedirect(req.getContextPath() + "/assets/html/home.jsp");
                return;
            } else {
                req.getSession().setAttribute("loginMsg", "密码不正确");
            }
        }
        resp.sendRedirect(req.getContextPath() + "/index.jsp");
    }

    public void register(HttpServletRequest req, HttpServletResponse resp) {
        String email = req.getParameter("email");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String password2 = req.getParameter("password2");
        try {
            if (!password.equals(password2)) {
                req.getSession().setAttribute("registerMsg", "确认密码不一致");
                resp.sendRedirect(req.getContextPath() + "/register.jsp");
                return;
            }
            Boolean count = userService.registerUser(email, username, password);
            if (count) {
                req.getSession().setAttribute("registerMsg", "注册成功");
                resp.sendRedirect(req.getContextPath() + "/index.jsp");
            } else {
                req.getSession().setAttribute("registerMsg", "注册失败");
                resp.sendRedirect(req.getContextPath() + "/register.jsp");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void checkEmail(HttpServletRequest req, HttpServletResponse resp) {
        String email = req.getParameter("email");
        HashMap<String, Object> map = new HashMap<>();
        map.put("email", email);
        List<User> userList = userService.findByT(map);
        try {
            if (userList == null || userList.size() == 0) {
                resp.getWriter().write("0");
            } else {
                resp.getWriter().write("1");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void checkName(HttpServletRequest req, HttpServletResponse resp) {
        String username = req.getParameter("username");
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", username);
        List<User> userList = userService.findByT(map);
        try {
            if (userList == null || userList.size() == 0) {
                resp.getWriter().write("0");
            } else {
                resp.getWriter().write("1");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendEmail(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String email = req.getParameter("email");
            HttpSession session = req.getSession();
            Object obj = session.getAttribute(email);
            if (obj != null) {
                resp.getWriter().write("邮箱已发送，请查收");
                return;
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("email", email);
            List<User> user = userService.findByT(map);
            if (user.size() == 0) {
                resp.getWriter().write("该邮箱账户不存在");
            } else {
                String code = userService.sendEmail(email);
                System.out.println("偷偷打印验证码：" + code);
                if (code.length() == 4) {
                    //发送成功，顺便保存到session中
                    session.setAttribute(email, code);
                    session.setMaxInactiveInterval(Constant.MAX_MAIL_TIME);
                    resp.getWriter().write("邮件发送成功");
                } else {
                    resp.getWriter().write("邮件发送失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void reset(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String email = req.getParameter("email");
            String code = req.getParameter("code");
            String password = req.getParameter("password");
            HashMap<String, Object> map = new HashMap<>();
            map.put("email", email);
            List<User> user = userService.findByT(map);
            if (null == user) {
                req.getSession().setAttribute("forgetMsg", "该邮箱账户不存在");
                resp.sendRedirect(req.getContextPath() + "/forget.jsp");
            } else {
                //校验code
                Object val = req.getSession().getAttribute(email);
                if (val == null) {
                    req.getSession().setAttribute("forgetMsg", "验证码已过期");
                    resp.sendRedirect(req.getContextPath() + "/forget.jsp");
                } else {
                    if (val.toString().equals(code)) {
                        //验证码通过
                        boolean b = userService.resetPassword(email, password);
                        if (b) {
                            req.getSession().setAttribute("loginMsg", "密码重置成功");
                            req.getSession().removeAttribute(email);
                            resp.sendRedirect(req.getContextPath() + "/index.jsp");
                        } else {
                            req.getSession().setAttribute("forgetMsg", "重置失败");
                            resp.sendRedirect(req.getContextPath() + "/forget.jsp");
                        }
                    } else {
                        req.getSession().setAttribute("forgetMsg", "验证码不正确");
                        resp.sendRedirect(req.getContextPath() + "/forget.jsp");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void logout(HttpServletRequest req, HttpServletResponse resp) {
        try {

            Cookie[] cookies = req.getCookies();
            for (Cookie cookie : cookies) {
                if ("username".equals(cookie.getName())) {
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    resp.addCookie(cookie);
                    break;
                }
            }
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
